package com.mall.common.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Pager;
import com.mall.common.bean.Pager.OrderType;
import com.mall.common.domain.content.TemplateDomain;
import com.mall.common.enums.TemplateType;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.TemplateService;
import com.mall.common.util.AppContext;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.Validations;

/**
 * 后台Action类 - 模板
 */
@Controller
@RequestMapping("/admin/system/template")
public class TemplateController  extends BaseController {

	@Resource private TemplateService templateService;
	
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping(value="/{type}/list", method=RequestMethod.GET)
	public String list(@PathVariable TemplateType type, Model model){
		model.addAttribute("type", type);
		return "/admin/system/template/list";
	}
	
	//获取列表
	@RequestMapping(value="/{type}/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(@PathVariable TemplateType type, Pager pager){
    	pager = templateService.queryByType(pager, type, "id", OrderType.asc);
		return JsonDataGridHelper.createJSONData(pager);
    }
    
	 /**
	 * 跳转到编辑页面
	 * @throws Exception 
	 */
	@RequestMapping(value="/{type}/edit/{id}", method=RequestMethod.GET)
	public String edit(@PathVariable Long id, @PathVariable TemplateType type, Model model) throws Exception{
		TemplateDomain template = templateService.find(id);
		if(template == null){
			throw new NoticeException("模板不存在");
		}
		if(template.getType() == null || template.getType() != type){
			throw new NoticeException("模板不存在");
		}
		File file = new File(AppContext.getAppRealPath("/WEB-INF/template/"+template.getPath()));
		if(!file.exists()){
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
				file.createNewFile();
			}else{
				file.createNewFile();
			}
		}
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis, "utf-8");
		BufferedReader br = new BufferedReader(isr);
		StringBuffer info = new StringBuffer("");
		String line = br.readLine();
		while(line != null) {
			info.append(line);
			info.append("\n");
			line = br.readLine();
		}
		if(br != null){
			br.close();
		}
		if(isr != null){
			isr.close();
		}
		if(fis != null){
			fis.close();
		}
		model.addAttribute("template", template);
		model.addAttribute("detail", info.toString());
		return "/admin/system/template/input";
	}
	
	/**
	 * 保存
	 * @return
	 * @throws Exception 
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "模板不存在!")
		}
	)
	@RequestMapping(value="/{type}/update", method=RequestMethod.POST)
	@ResponseBody
	public String save(Long id, @PathVariable TemplateType type, 
			String detail,  HttpServletResponse response) throws Exception{
		String error = templateService.save(id, type, detail);
		if(StringUtils.isNotBlank(error)){
			throw new NoticeException(error);
		}
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
}
